<?php

namespace plugin\admin\app\controller;

use app\common\model\SendMsg;
use support\Log;
use support\Request;
use support\Response;
use plugin\admin\app\model\AcSendMsg;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 消息列表
 */
class AcSendMsgController extends Crud
{

    /**
     * @var AcSendMsg
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new AcSendMsg;
    }

    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('ac-send-msg/index');
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::insert($request);
        }
        return view('ac-send-msg/insert');
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
    */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }
        return view('ac-send-msg/update');
    }
    // 更新待发送状态
    public function send(Request $request): Response
    {
        $id = $request->post('id', '');

        if (empty($id)) {
            return $this->fail(1, '参数不能为空');
        }

        $data['status'] = 1;
        $this->doUpdate($id, $data);
        return $this->json(0);
    }
    // 发送消息中
    public function fcmSendMsg(Request $request): Response
    {
        $sendMsgModel = new \app\common\model\SendMsg();
        try {
            // 查询要发送的消息
            $sendMsg = $sendMsgModel->field('id,title,content')->where(['status' => 1])
                ->order(['id' => 'desc'])->find();

            // 向主题发送
            $title = $sendMsg['title'] ?? '你有一条新消息';
            $body = $sendMsg['content'] ?? '你有一条新消息';
            $topicName = env('SYSTEM_TOPIC');
            // 主题推送消息
            $fcmTopicBus =new \app\common\business\sendFcm\FcmTopic();
            $sendTopicMsg = $fcmTopicBus::sendTopicMsg($topicName, $title, $body);
            if ($sendTopicMsg) {
                // 查询主题是否存在
                $topicModel = new \app\common\model\Topics();
                $topic = $topicModel->getFindData(['topic' => $topicName], 'id,topic,nums', ['id'=>'desc']);
                // 添加消息记录
                (new \app\common\model\SendLog())->insertGetId([
                    'topic_id' => $topic['id'] ?? 0,
                    'msg_id' => $sendMsg['id'] ?? 0,
                    'type' => 1,
                    'created_at' => time()
                ]);
                if ($sendMsg) {
                    $sendMsgModel->where(['id' => $sendMsg['id']])->update(['status' => 2, 'updated_at' => time()]);
                }
            }

//            if (!empty($sendMsg)) {
//                $userFcmTokenModel = new \app\common\model\UserFcmToken();

//                $users = $userFcmTokenModel->field('id,user_id,fcm_token')
//                    ->where([['exp_time', '>', time() - (30 * 86400)]])
//                    ->order(['id'=>'asc'])
//                    ->cursor();
//                if (!empty($users)) {
//                    $fcmMessageBus = new \app\common\business\sendFcm\FcmMessage();
//                    $i=0;
//                    $logId=0;
//                    foreach ($users as $user) {
//                        $AccessToken = $fcmMessageBus::getFirebaseAccessToken();
//                        $vidToken = $fcmMessageBus::validateFcmToken($AccessToken, $user['fcm_token']);
//                        Log::info('$vidToken--info:'.json_encode($vidToken));
//                        if (isset($vidToken['isValid']) && $vidToken['isValid']==true) {
//                            $i++;
//                            $logId = $fcmMessageBus::fcmSend($user, $sendMsg);
//                        } else {
//                            $userFcmTokenModel->where(['fcm_token'=>$user['fcm_token']])->delete();
//                        }
//                    }
//                    Log::info('$logId--info:'.$i.'--'.$logId);
//                    if (!empty($logId)) {
//                        $sendMsgModel->where(['id' => $sendMsg['id']])->update(['status' => 2, 'updated_at' => time()]);
//                        (new \app\common\model\SendLog())->where(['id'=>$logId])->update(['type'=>1,'updated_at' => time()]);
//                    } else {
//                        return $this->json(2, '暂无发送用户');
//                    }
//                }
//            }
        } catch (\Exception $e) {
            Log::error('发送失败--error：'.$e->getMessage().$e->getFile().$e->getLine());
            $sendMsgModel::where(['id' => $sendMsg['id']])->update([
                'status' => 0,
                'updated_at' => time()
            ]);
            return $this->json(1);
        }

        return $this->json(0);
    }

}
